package lowijs.XfireClient.packet;

import lowijs.XfireClient.*;
import lowijs.XfireClient.event.EventManager;
import lowijs.XfireClient.event.ScreenshotsEvent;
import lowijs.XfireClient.util.Util;

import java.util.*;

public class ScreenshotsPacket extends Packet {
	public ScreenshotsPacket(byte[] data) {
		ArrayList<Screenshot> screenshots = new ArrayList<Screenshot>();
		
		int pos = Util.findByteArray(data, new byte[] { 0x54, 0x04, 0x01 });
		pos += 3; // jump to num screenies
		
		int numScreens = fromLowHigh(data[pos], data[pos + 1]);
		if (numScreens == 0) {
			EventManager.fireEvent(new ScreenshotsEvent(null));
			return;
		}
		
		pos += 2; // jump to description length
		
		for (int i = 0; i < numScreens; i++) {
			int len = fromLowHigh(data[pos], data[pos + 1]);
			if (len == 0) {
				screenshots.add(new Screenshot("No description."));
				pos += 2;
				continue;
			}
			byte[] desc = new byte[len];
			System.arraycopy(data, pos + 2, desc, 0, desc.length);
			screenshots.add(new Screenshot(new String(desc)));
			pos += len + 2;
		}
		
		pos = Util.findByteArray(data, new byte[] { 0x21, 0x04, 0x02 });
		pos += 5;
		
		for (int i = 0; i < numScreens; i++) {
			int gameid = Util.intFromBytes(data, pos, 4);
			getGamedataById(gameid);
			screenshots.get(i).setGamename(gamename);
			pos += 4;
		}
		
		pos = Util.findByteArray(data, new byte[] { 0x50, 0x04, 0x02 });
		pos += 5;
		
		for (int i = 0; i < numScreens; i++) {
			long timestamp = Util.longFromBytes(data, pos, 4);
			Date date = new Date(timestamp * 1000);
			screenshots.get(i).setDate(date);
			pos += 4;
		}
		
		pos = Util.findByteArray(data, new byte[] { 0x5e, 0x04, 0x01 });
		pos += 7; // jump to screenshot GUID
		
		for (int i = 0; i < numScreens; i++) {
			byte[] guidBytes = new byte[38];
			System.arraycopy(data, pos, guidBytes, 0, guidBytes.length);
			screenshots.get(i).setGuid(Util.toSHA1(new String(guidBytes)));
			pos += 40;
		}
		
		EventManager.fireEvent(new ScreenshotsEvent(screenshots));
	}
}
